package com.canbot.u05.view;

import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.canbot.u05.R;

public class PasswordLayout extends LinearLayout implements KeyboardLayout.OnkeyBoardClickListener {

    private static final String TAG = "PasswordLayout";
    private Context context;
    private static final String KEY_COMPLETE = "complete";
    private static final String KEY_DELETE = "delete";

    int index = -1;

    private final int LENGTH = 6; //密码输入框位数

    private OnPasswordChangeListener lisener;
    private KeyboardLayout keyBoard;
    private StringBuffer passwordBuffer;
    private Handler handler = new Handler();

    public PasswordLayout(Context context) {
        super(context);
    }

    public PasswordLayout(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        setOrientation(HORIZONTAL);
        this.context = context;
        addChildView();
        passwordBuffer = new StringBuffer();
    }

    public PasswordLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    /**
     * 添加密码框控件
     */
    private void addChildView() {

        for (int i = 0; i <LENGTH; i++) {
            TextView textView = new TextView(context);
            textView.setGravity(Gravity.CENTER);
            textView.setTextSize(48);
            textView.setTextColor(Color.parseColor("#333333"));
            textView.setBackgroundResource(R.drawable.shape_password_bg);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams((int) 120, 120);
            if (i != LENGTH -1){
                params.rightMargin = (int) 50;
            }
            textView.setLayoutParams(params);

            addView(textView);

        }

    }

    /**
     * 关联键盘
     * @param keyBoard
     */
    public void setKeyBoard(KeyboardLayout keyBoard){
        this.keyBoard = keyBoard;
        if (keyBoard != null){
            keyBoard.setOnkeyBoardClickListener(this);
        }
    }

    /**
     * 清楚密码状态
     */
    public void clear(){
        keyBoard.setCompleteEnable(false); //确定键不可点击
        int length = passwordBuffer.length();
        passwordBuffer.delete(0,length);  //密码数据清空
        index = -1;
        for (int i = 0; i < LENGTH; i++) {
            TextView tv = (TextView) getChildAt(i);
            tv.setText("");//密码框界面清空
        }
    }


    public void setOnPasswordChangeLisener(OnPasswordChangeListener lisener){
        this.lisener = lisener;
    }

    /**
     * 键盘点击时的回调
     * @param key
     */
    @Override
    public void onkeyBoadrClick(String key) {
        if (key.equals(KEY_COMPLETE) ){

            String password = passwordBuffer.toString();
            String encodePassword = Base64.encodeToString(password.getBytes(), Base64.DEFAULT);
            if (lisener != null){
                lisener.onComplete(encodePassword);
            }

        }else if (key.equals(KEY_DELETE)){
            deletePassword();
        }else{
            insertPassword(key);
        }
    }

    private void insertPassword(String key) {
        index++;
        if (index >= LENGTH){
            index = LENGTH-1;
            return;
        }
        if (lisener != null){
            lisener.inputting();
        }
        final TextView tv = (TextView) getChildAt(index);
        tv.setText(key);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                tv.setText("*");
            }
        },200);

        passwordBuffer.append(key);

        if (index == LENGTH -1){
//            keyBoard.setCompleteEnable(true);
            handler.removeCallbacksAndMessages(null);
            String password = passwordBuffer.toString();
            String encodePassword = Base64.encodeToString(password.getBytes(), Base64.DEFAULT);
            if (lisener != null){
                lisener.onComplete(encodePassword);
            }
        }

    }

    private void deletePassword() {

        if (index < 0){
            index = -1;
            return;
        }

        handler.removeCallbacksAndMessages(null);
        final TextView tv = (TextView) getChildAt(index);
        tv.setText("");
        passwordBuffer.deleteCharAt(index);
        index--;

        if (index != LENGTH -1){
            keyBoard.setCompleteEnable(false);
        }
    }

    public interface OnPasswordChangeListener {
        void onComplete(String encodePassword);
        void inputting();
    }
}
